#include "statemanager.h"
#include "abstractstate.h"

StateManager::StateManager(QObject *parent) :
    QObject(parent)
{
}

void StateManager::registerState(QPointer<AbstractState> state)
{
    m_states << state;
}

void StateManager::changeState(const QString &stateId)
{
    changeState(stateById(stateId));
}

void StateManager::changeState(QPointer<AbstractState> state)
{
    if(m_currentState)
    {
        m_currentState->exit();
    }

    emit currentStateAboutToChange();
    m_currentState = state;

    if(m_currentState)
    {
        m_currentState->enter();
    }

    emit currentStateChanged();
}

QPointer<AbstractState> StateManager::currentState() const
{
    return m_currentState;
}

QPointer<AbstractState> StateManager::stateById(const QString &sid)
{
    QPointer<AbstractState> result;

    foreach(QPointer<AbstractState> state, m_states)
    {
        if(state->stateId() == sid)
        {
            result = state;
            break;
        }
    }

    return result;
}

const StateManager::States& StateManager::states() const
{
	return m_states;
}
